# diagnose_tts.py - TTS问题快速诊断脚本
import os
import sys
import logging

# 设置详细日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)


def check_config():
    """检查配置"""
    print("🔧 检查配置...")

    try:
        from config import SPARK_APPID, SPARK_APIKey, SPARK_APISecret

        print(f"✅ SPARK_APPID: {SPARK_APPID}")
        print(f"✅ SPARK_APIKey: {SPARK_APIKey[:8]}...")
        print(f"✅ SPARK_APISecret: {SPARK_APISecret[:8]}...")

        # 验证配置不是默认值
        if SPARK_APPID == "your_spark_app_id":
            print("❌ SPARK_APPID 是默认值，需要配置真实值")
            return False

        return True

    except ImportError as e:
        print(f"❌ 配置导入失败: {e}")
        return False


def check_dependencies():
    """检查依赖"""
    print("\n📦 检查依赖...")

    deps = {
        'websocket': 'websocket-client',
        'wave': '内置模块',
        'ssl': '内置模块',
        'json': '内置模块'
    }

    for module, install_name in deps.items():
        try:
            __import__(module.replace('-', '_'))
            print(f"✅ {module}")
        except ImportError:
            print(f"❌ {module} - 安装: pip install {install_name}")
            return False

    return True


def test_url_creation():
    """测试URL创建"""
    print("\n🌐 测试URL创建...")

    try:
        from tts import create_tts_url

        url = create_tts_url()
        if url:
            print(f"✅ TTS URL创建成功")
            print(f"🔗 URL: {url[:50]}...")
            return True
        else:
            print("❌ TTS URL创建失败")
            return False

    except Exception as e:
        print(f"❌ URL创建异常: {e}")
        return False


def test_simple_synthesis():
    """测试简单语音合成"""
    print("\n🎙️ 测试简单语音合成...")

    try:
        from tts import synthesize_and_play, get_audio_file_path

        # 使用最简单的文本
        test_text = "你好"
        print(f"🔊 测试文本: '{test_text}'")

        # 清理旧文件
        for filename in ["demo.pcm", "demo.wav"]:
            if os.path.exists(filename):
                os.remove(filename)
                print(f"🧹 清理旧文件: {filename}")

        print("🔄 开始合成...")
        success = synthesize_and_play(test_text)

        if success:
            print("✅ 语音合成成功")

            # 检查文件
            audio_path = get_audio_file_path()
            if audio_path and os.path.exists(audio_path):
                file_size = os.path.getsize(audio_path)
                print(f"📁 音频文件: {audio_path}")
                print(f"📊 文件大小: {file_size} bytes")

                if file_size > 1000:  # 正常文件应该大于1KB
                    print("✅ 文件大小正常")
                    return True
                else:
                    print("⚠️ 文件太小，可能有问题")
                    return False
            else:
                print("❌ 音频文件不存在")
                return False
        else:
            print("❌ 语音合成失败")
            return False

    except Exception as e:
        print(f"❌ 测试异常: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_longer_text():
    """测试较长文本"""
    print("\n📝 测试较长文本...")

    try:
        from tts import synthesize_and_play, get_audio_file_path

        test_text = "请简单介绍一下您自己，包括教育背景和工作经验。"
        print(f"🔊 测试文本: '{test_text}'")

        success = synthesize_and_play(test_text)

        if success:
            audio_path = get_audio_file_path()
            if audio_path and os.path.exists(audio_path):
                file_size = os.path.getsize(audio_path)
                print(f"✅ 较长文本合成成功: {file_size} bytes")
                return True
            else:
                print("❌ 音频文件生成失败")
                return False
        else:
            print("❌ 较长文本合成失败")
            return False

    except Exception as e:
        print(f"❌ 测试异常: {e}")
        return False


def test_problematic_text():
    """测试之前有问题的文本"""
    print("\n🔍 测试问题文本...")

    try:
        from tts import synthesize_and_play, get_audio_file_path

        # 之前导致问题的文本
        problem_text = "在您参与的项目中，您作为项目经理遇到了哪些挑战？"
        print(f"🔊 问题文本: '{problem_text}'")

        success = synthesize_and_play(problem_text)

        if success:
            audio_path = get_audio_file_path()
            if audio_path and os.path.exists(audio_path):
                file_size = os.path.getsize(audio_path)
                print(f"✅ 问题文本合成成功: {file_size} bytes")
                print("💡 建议手动播放音频文件检查是否有结巴")
                return True
            else:
                print("❌ 音频文件生成失败")
                return False
        else:
            print("❌ 问题文本合成失败")
            return False

    except Exception as e:
        print(f"❌ 测试异常: {e}")
        return False


def play_last_audio():
    """播放最后生成的音频"""
    print("\n🔊 尝试播放最后的音频文件...")

    try:
        from tts import get_audio_file_path

        audio_path = get_audio_file_path()
        if audio_path and os.path.exists(audio_path):
            print(f"📁 音频文件: {audio_path}")

            # 尝试播放
            if os.name == 'nt':  # Windows
                os.system(f'start "" "{audio_path}"')
                print("✅ 已在Windows默认播放器中打开音频")
            elif sys.platform == 'darwin':  # macOS
                os.system(f'open "{audio_path}"')
                print("✅ 已在macOS默认播放器中打开音频")
            else:  # Linux
                os.system(f'xdg-open "{audio_path}"')
                print("✅ 已在Linux默认播放器中打开音频")

        else:
            print("❌ 没有找到音频文件")

    except Exception as e:
        print(f"❌ 播放失败: {e}")


def main():
    print("🔧 TTS问题诊断工具")
    print("=" * 50)

    tests = [
        ("配置检查", check_config),
        ("依赖检查", check_dependencies),
        ("URL创建测试", test_url_creation),
        ("简单合成测试", test_simple_synthesis),
        ("较长文本测试", test_longer_text),
        ("问题文本测试", test_problematic_text)
    ]

    results = []

    for test_name, test_func in tests:
        print(f"\n{'=' * 20} {test_name} {'=' * 20}")
        try:
            result = test_func()
            results.append((test_name, result))

            if result:
                print(f"✅ {test_name} 通过")
            else:
                print(f"❌ {test_name} 失败")

        except Exception as e:
            print(f"❌ {test_name} 异常: {e}")
            results.append((test_name, False))

    # 汇总结果
    print(f"\n{'=' * 50}")
    print("📊 诊断结果汇总:")

    passed = 0
    for test_name, result in results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"  {test_name}: {status}")
        if result:
            passed += 1

    print(f"\n总体结果: {passed}/{len(tests)} 测试通过")

    if passed == len(tests):
        print("🎉 所有测试通过！TTS功能正常")
        play_last_audio()
    elif passed >= 4:
        print("⚠️ 大部分测试通过，TTS基本功能正常")
        play_last_audio()
    else:
        print("❌ 多项测试失败，TTS功能异常")
        print("\n🔧 故障排除建议:")
        print("1. 检查网络连接")
        print("2. 验证API密钥和配额")
        print("3. 确认websocket-client已安装")
        print("4. 尝试重新安装依赖包")


if __name__ == "__main__":
    main()